package org.dromara.app.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotEmpty;
import org.dromara.app.appParams.AppApplyForWithdrawalParams;
import org.dromara.app.cssUtils.CssExceptionDescription;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.domain.SkAppUser;
import org.dromara.app.domain.SkPriceLog;
import org.dromara.app.domain.SkVipPrice;
import org.dromara.app.mapper.SkAppUserMapper;
import org.dromara.app.mapper.SkPriceLogMapper;
import org.dromara.app.service.ISkPriceLogService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.SkWithdrawalLogBo;
import org.dromara.app.domain.vo.SkWithdrawalLogVo;
import org.dromara.app.domain.SkWithdrawalLog;
import org.dromara.app.mapper.SkWithdrawalLogMapper;
import org.dromara.app.service.ISkWithdrawalLogService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 提现信息LOGService业务层处理
 *
 * @author Evacuation
 * @date 2024-07-23
 */
@RequiredArgsConstructor
@Service
public class SkWithdrawalLogServiceImpl implements ISkWithdrawalLogService {

    private final SkWithdrawalLogMapper baseMapper;

    private final SkAppUserMapper skAppUserMapper;

   private final SkPriceLogMapper skPriceLogMapper;
    /**
     * 查询提现信息LOG
     *
     * @param id 主键
     * @return 提现信息LOG
     */
    @Override
    public SkWithdrawalLogVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询提现信息LOG列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 提现信息LOG分页列表
     */
    @Override
    public TableDataInfo<SkWithdrawalLogVo> queryPageList(SkWithdrawalLogBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<SkWithdrawalLog> lqw = buildQueryWrapper(bo);
        Page<SkWithdrawalLogVo> result = baseMapper.selectVoNewPage(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的提现信息LOG列表
     *
     * @param bo 查询条件
     * @return 提现信息LOG列表
     */
    @Override
    public List<SkWithdrawalLogVo> queryList(SkWithdrawalLogBo bo) {
        LambdaQueryWrapper<SkWithdrawalLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkWithdrawalLog> buildQueryWrapper(SkWithdrawalLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SkWithdrawalLog> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getPrice() != null, SkWithdrawalLog::getPrice, bo.getPrice());
        lqw.eq(bo.getType() != null, SkWithdrawalLog::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getImage()), SkWithdrawalLog::getImage, bo.getImage());
        lqw.eq(bo.getCommission() != null, SkWithdrawalLog::getCommission, bo.getCommission());
        return lqw;
    }

    /**
     * 新增提现信息LOG
     *
     * @param bo 提现信息LOG
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SkWithdrawalLogBo bo) {
        SkWithdrawalLog add = MapstructUtils.convert(bo, SkWithdrawalLog.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改提现信息LOG
     *
     * @param bo 提现信息LOG
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SkWithdrawalLogBo bo) {
        SkWithdrawalLog update = MapstructUtils.convert(bo, SkWithdrawalLog.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkWithdrawalLog entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除提现信息LOG信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 申请提现
     * @param params
     * @param req
     */
    @Override
    public void applyForWithdrawal(AppApplyForWithdrawalParams params, HttpServletRequest req) {

        Long userId = CssUtils.getUserId(req);
        SkAppUser skAppUser = skAppUserMapper.selectById(userId);
        if (skAppUser.getPrice().compareTo(params.getPrice())<0){
            CssExceptionDescription.errorMsg(10014);
        }
        //生成提现记录
        SkWithdrawalLog sk = new SkWithdrawalLog();
        sk.setType(params.getType());
        sk.setUserId(userId);
        sk.setImage(params.getImage());
        sk.setPrice(params.getPrice());
        sk.setState(0L);
        baseMapper.insert(sk);
    }

    /**
     * 确认打款
     *
     * @param ids
     * @param isValid
     * @return
     */
    @Override
    public int sumbitConfirmPayment(Collection<Long> ids, Boolean isValid) {
        return 0;
    }

    @Override
    public SkWithdrawalLog getOneByUserId(Long userId) {
        SkWithdrawalLog log = baseMapper.selectOne(Wrappers.
            <SkWithdrawalLog>lambdaQuery().eq(SkWithdrawalLog::getUserId, userId).eq(SkWithdrawalLog::getState,0).last("limit 1"));
        return log;
    }

    @Override
    public SkWithdrawalLog getOneById(String logId) {
        return baseMapper.selectById(logId);
    }

    /**
     * 拒绝提现
     *
     * @param ids
     * @param b
     * @return
     */
    @Override
    public int withdrawimmediatelyjujue(Long ids, boolean b) {
        SkWithdrawalLog sk = baseMapper.selectById(ids);
        if (sk!=null && sk.getState()==0L){
            sk.setState(2L);
            //回退余额
            SkAppUser skAppUser = skAppUserMapper.selectById(sk.getUserId());
            activevipAccount(skAppUser,sk.getPrice(),18L,"提现拒绝");
        }else {
            throw new RuntimeException("提现记录不存在或已处理");
        }
        return  baseMapper.updateById(sk);
    }


    /**
     * 开通会员余额操作
     *
     * @param skAppUser
     * @param price
     * @param type
     * @param content
     */
    public void activevipAccount(SkAppUser skAppUser, BigDecimal price, Long type, String content) {
        SkPriceLog sk = new SkPriceLog();
        sk.setPrice(price);
        sk.setUserId(skAppUser.getId());
        sk.setOldPrice(skAppUser.getPrice());
        sk.setType(type);
        sk.setTitle(content);
        skPriceLogMapper.insert(sk);
        skAppUserMapper.activePrice(skAppUser.getId(), sk.getPrice());
    }
}
